package top.lyunk.demo.zk;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * <pre>
 * 说明：
 * </pre>
 *
 * @author lyk
 * @date 2022/9/15
 */
public class ZookeeperClientApp {
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        System.out.println(ClientCnxnSocketNetty.class.getSimpleName());
        // ZooKeeper zk = new ZooKeeper("127.0.0.1", 60 * 1000, new MyWatcher());
        // // 临时节点下无法创建临时节点，将父节点设置为永久节点
        // createNode(zk, "/demo", "hello", CreateMode.PERSISTENT);
        // zk = new ZooKeeper("127.0.0.1/demo", 60 * 1000, new MyWatcher());
        // String nodeName = createNode(zk, "/b", "hello", CreateMode.EPHEMERAL_SEQUENTIAL);
        // System.out.println(nodeName);
        //
        // Thread.sleep(60 * 1000);
    }

    private static String createNode(ZooKeeper zk, String node, String data, CreateMode createMode) throws KeeperException, InterruptedException {
        return zk.create(node, data.getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                // new ArrayList<>(List.of(
                //         // 给创建者所有权限
                //         new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.AUTH_IDS),
                //         // 给其他用户阅读权限
                //         new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)
                // )),
                createMode);
    }

    public static class MyWatcher implements Watcher {

        @Override
        public void process(WatchedEvent event) {
            System.out.println("path=" + event.getPath());
            System.out.println("state=" + event.getState());
            System.out.println("type=" + event.getType());
            String msg = switch (event.getState()){
                case Disconnected -> null;
                case SyncConnected -> "建立连接";
                case AuthFailed -> null;
                case ConnectedReadOnly -> null;
                case SaslAuthenticated -> null;
                case Expired -> null;
                case Closed -> null;
                default -> "未知";
            };
            System.out.println("当前state=" + msg);
        }
    }
}
